<?php

// 未完成功能提醒：76行左右，语言包缓存功能没有做

if(!defined('IN_SING')) {
	exit('Access Denied');
}

define('SING_CORE_FUNCTION', true);

//转意函数
function new_addslashes($string)
{
	if(!is_array($string)) return addslashes($string);
	foreach($string as $key => $val) $string[$key] = new_addslashes($val);
	return $string;
}

function return_bytes($val) {
	$val = trim($val);
	$last = strtolower($val{strlen($val)-1});
	switch($last) {
		case 'g': $val *= 1024;
		case 'm': $val *= 1024;
		case 'k': $val *= 1024;
	}
	return $val;
}

function checkrobot($useragent = '') {
	static $kw_spiders = array('bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla');
	static $kw_browsers = array('msie', 'netscape', 'opera', 'konqueror', 'mozilla');

	$useragent = strtolower(empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent);
	if(strpos($useragent, 'http://') === false && dstrpos($useragent, $kw_browsers)) return false;
	if(dstrpos($useragent, $kw_spiders)) return true;
	return false;
}

function dstrpos($string, $arr, $returnvalue = false) {
	if(empty($string)) return false;
	foreach((array)$arr as $v) {
		if(strpos($string, $v) !== false) {
			$return = $returnvalue ? $v : true;
			return $return;
		}
	}
	return false;
}

function getglobal($key, $group = null) {
	global $_G;
	$key = explode('/', $group === null ? $key : $group.'/'.$key);
	$v = &$_G;
	foreach ($key as $k) {
		if (!isset($v[$k])) {
			return null;
		}
		$v = &$v[$k];
	}
	return $v;
}

function lang($file, $langvar = null, $vars = array(), $default = null) {
	global $_G;
	$scriptlang = array();
	$fileinput = $file;
	list($path, $file) = explode('/', $file);
	if(!$file) {
		$file = $path;
		$path = '';
	}
	if(strpos($file, ':') !== false) {
		$path = 'plugin';
		list($file) = explode(':', $file);
	}
	$lang = '';
	if($path != 'plugin') {
		$key = $path == '' ? $file : $path.'_'.$file;
		if(!isset($_G['lang'][$key])) {
			include SING_PATH.'/source/language/'.($path == '' ? '' : $path.'/').'lang_'.$file.'.php';
			$_G['lang'][$key] = $lang;
		}
		if(defined('IN_MOBILE') && !defined('TPL_DEFAULT')) {
			include SING_PATH.'/source/language/mobile/lang_template.php';
			$_G['lang'][$key] = array_merge($_G['lang'][$key], $lang);
		}
		if($file != 'error' && !isset($_G['cache']['pluginlanguage_system'])) {
			//loadcache('pluginlanguage_system');
		}
		if(!isset($_G['hooklang'][$fileinput])) {
			if(isset($_G['cache']['pluginlanguage_system'][$fileinput]) && is_array($_G['cache']['pluginlanguage_system'][$fileinput])) {
				$_G['lang'][$key] = array_merge($_G['lang'][$key], $_G['cache']['pluginlanguage_system'][$fileinput]);
			}
			$_G['hooklang'][$fileinput] = true;
		}
		$returnvalue = &$_G['lang'];
	} else {
		if(empty($_G['config']['plugindeveloper'])) {
			loadcache('pluginlanguage_script');
		} elseif(!isset($_G['cache']['pluginlanguage_script'][$file]) && preg_match("/^[a-z]+[a-z0-9_]*$/i", $file)) {
			if(@include(SING_PATH.'/data/plugindata/'.$file.'.lang.php')) {
				$_G['cache']['pluginlanguage_script'][$file] = $scriptlang[$file];
			} else {
				loadcache('pluginlanguage_script');
			}
		}
		$returnvalue = & $_G['cache']['pluginlanguage_script'];
		$key = &$file;
	}
	$return = $langvar !== null ? (isset($returnvalue[$key][$langvar]) ? $returnvalue[$key][$langvar] : null) : $returnvalue[$key];
	$return = $return === null ? ($default !== null ? $default : $langvar) : $return;
	$searchs = $replaces = array();
	if($vars && is_array($vars)) {
		foreach($vars as $k => $v) {
			$searchs[] = '{'.$k.'}';
			$replaces[] = $v;
		}
	}
	if(is_string($return) && strpos($return, '{_G/') !== false) {
		preg_match_all('/\{_G\/(.+?)\}/', $return, $gvar);
		foreach($gvar[0] as $k => $v) {
			$searchs[] = $v;
			$replaces[] = getglobal($gvar[1][$k]);
		}
	}
	$return = str_replace($searchs, $replaces, $return);
	return $return;
}

function system_error($message, $show = true, $save = true, $halt = true) {
	SING_error::system_error($message, $show, $save, $halt);
}

function dhtmlspecialchars($string, $flags = null) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dhtmlspecialchars($val, $flags);
		}
	} else {
		if($flags === null) {
			$string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
			if(strpos($string, '&amp;#') !== false) {
				$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
			}
		} else {
			if(PHP_VERSION < '5.4.0') {
				$string = htmlspecialchars($string, $flags);
			} else {
				if(strtolower(CHARSET) == 'utf-8') {
					$charset = 'UTF-8';
				} else {
					$charset = 'ISO-8859-1';
				}
				$string = htmlspecialchars($string, $flags, $charset);
			}
		}
	}
	return $string;
}

function dstripslashes($string) {
	if(empty($string)) return $string;
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = dstripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}

function daddslashes($string, $force = 1) {
	if(is_array($string)) {
		$keys = array_keys($string);
		foreach($keys as $key) {
			$val = $string[$key];
			unset($string[$key]);
			$string[addslashes($key)] = daddslashes($val, $force);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}


function setglobal($key , $value, $group = null) {
	global $_G;
	$key = explode('/', $group === null ? $key : $group.'/'.$key);
	$p = &$_G;
	foreach ($key as $k) {
		if(!isset($p[$k]) || !is_array($p[$k])) {
			$p[$k] = array();
		}
		$p = &$p[$k];
	}
	$p = $value;
	return true;
}

//加载模板
function admin_tpl($module = '',$file = 'index')
{
	global $client;
	//移动端判断
	$agent = strtolower($_SERVER['HTTP_USER_AGENT']);   
	$is_iphone = (strpos($agent, 'iphone')) ? true : false;   
	$is_ipad = (strpos($agent, 'ipad')) ? true : false;   
	$is_android = (strpos($agent, 'android')) ? true : false;
	$is_at = (strpos($agent, 'sichem_at')) ? true : false;
	
	if($is_iphone) $mobile = 'iphone/';
	if($is_ipad||$client) $mobile = 'ipad/';
	if($is_android) $mobile = 'android/';	
	if($is_at) $mobile = 'at/';
	
	//模块模板
	if($module){
		//如果存在移动端模板就加载
		if(is_file(APP_ROOT.'/module/'.$module.'/templates/'.$mobile.$file.'.tpl.php')) return APP_ROOT.'/module/'.$module.'/templates/'.$mobile.$file.'.tpl.php';		
		//没有返回移动端模板
		//判断PC版模板是否存在并且返回
		if(is_file(APP_ROOT.'/module/'.$module.'/templates/'.$file.'.tpl.php')) return APP_ROOT.'/module/'.$module.'/templates/'.$file.'.tpl.php';
		else system_error( '/module/'.$module.'/templates/'.$file.'.tpl.php 不存在！');
	}

	//加载系统模板
	if(is_file(APP_ROOT.'/manage/'.$mobile.$file.'.tpl.php')) return APP_ROOT.'/manage/'.$mobile.$file.'.tpl.php';
	if(is_file(APP_ROOT.'/manage/'.$file.'.tpl.php')) return APP_ROOT.'/manage/'.$file.'.tpl.php'; 
	else system_error('/manage/'.$file.'.tpl.php 不存在！');
}

function DoHTML($dir){
	include $dir;
}

function SING_auth($txt, $operation = 'ENCODE', $key = '')
{
	$key	= $key ? $key : $GLOBALS['phpcms_auth_key'];
	$txt	= $operation == 'ENCODE' ? $txt : base64_decode($txt);
	$len	= strlen($key);
	$code	= '';
	for($i=0; $i<strlen($txt); $i++){
		$k		= $i % $len;
		$code  .= $txt[$i] ^ $key[$k];
	}
	$code = $operation == 'DECODE' ? $code : base64_encode($code);
	return $code;
}

function is_ajax_request(){
	if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')	return true;	
	else return false;
}
function dintval($int, $allowarray = false) {
	$ret = intval($int);
	if($int == $ret || !$allowarray && is_array($int)) return $ret;
	if($allowarray && is_array($int)) {
		foreach($int as &$v) {
			$v = dintval($v, true);
		}
		return $int;
	} elseif($int <= 0xffffffff) {
		$l = strlen($int);
		$m = substr($int, 0, 1) == '-' ? 1 : 0;
		if(($l - $m) === strspn($int,'0987654321', $m)) {
			return $int;
		}
	}
	return $ret;
}

function dsetcookie($var, $value = '', $life = 0, $prefix = 1, $httponly = false) {

	global $_G;

	$config = $_G['config']['cookie'];

	$_G['cookie'][$var] = $value;
	$var = ($prefix ? $config['cookiepre'] : '').$var;
	$_COOKIE[$var] = $value;

	if($value == '' || $life < 0) {
		$value = '';
		$life = -1;
	}

	if(defined('IN_MOBILE')) {
		$httponly = false;
	}

	$life = $life > 0 ? getglobal('timestamp') + $life : ($life < 0 ? getglobal('timestamp') - 31536000 : 0);
	$path = $httponly && PHP_VERSION < '5.2.0' ? $config['cookiepath'].'; HttpOnly' : $config['cookiepath'];

	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	if(PHP_VERSION < '5.2.0') {
		setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure);
	} else {
		setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure, $httponly);
	}
}

function getcookie($key) {
	global $_G;
	return isset($_G['cookie'][$key]) ? $_G['cookie'][$key] : '';
}

function CheckAuth($module = '', $act ='' ){
	global $_G;
	$mysa = array();
	$uids = array();
	$deid = $_G['deid']; 
	$groupid = $_G['groupid'];
	$s = $_G['s'];
	
	$sa = $_G['sa'];
	$group = $sa[$module];
	$do = $group[$groupid];
	$my = $group[$groupid][$act]['digit'];
	foreach($group as $k => $v){
		if($v[$act]['level']){
			if($my >= $v[$act]['digit']) $mysa[] = $k;
		}else{
			if($my > $v[$act]['digit']) $mysa[] = $k;
		}
	}
	$r = DB::result_first('select descendants from %t where deid=%d',array('department', $deid));
	if($r){
		$deids = explode(',',$r);
		$deids[] = $deid;
		$mids = DB::fetch_all('select memberid from %t where deid in (%n) and groupid in (%n)',array('member', $deids, $mysa));
		foreach($mids as $v){
			$uids[] = intval($v['memberid']);
		}
	}
	$uids[] = intval($_G['uid']);
	//var_dump($uids);
	return $uids;
}

//缓存方法
function memory($cmd, $key='', $value='', $ttl = 0, $prefix = '') {
	if($cmd == 'check') {
		return  C::memory()->enable ? C::memory()->type : '';
	} elseif(C::memory()->enable && in_array($cmd, array('set', 'get', 'rm', 'inc', 'dec'))) {

		switch ($cmd) {
			case 'set': return C::memory()->set($key, $value, $ttl, $prefix); break;
			case 'get': return C::memory()->get($key, $value); break;
			case 'rm': return C::memory()->rm($key, $value); break;
			case 'inc': return C::memory()->inc($key, $value ? $value : 1); break;
			case 'dec': return C::memory()->dec($key, $value ? $value : -1); break;
		}
	}
	return null;
}

//redis 缓存方法
function redis2($cmd, $key='', $value ='', $ttl = 0 , $prefix = ''){
	if($cmd == 'check') {
		return  C::redis()->enable ? C::redis()->type : '';
	} elseif(C::redis()->enable && in_array($cmd, array('zadd','zrem','zcount','zrange','zscore','zcard','zremrangebyscore','zremrangebyrank','set', 'get', 'rm', 'inc', 'dec'))) {

		switch ($cmd) {
			case 'zadd': return C::redis()->zadd($key, $value, $prefix); break;
			case 'zrem': return C::redis()->zrem($key, $value, $prefix); break;
			case 'zcount': return C::redis()->zcount($key, $value, $prefix); break;
			case 'zrange': return C::redis()->zrange($key, $value, $prefix); break;
			case 'zscore': return C::redis()->zscore($key, $value, $prefix); break;
			case 'zcard': return C::redis()->zcard($key, $prefix); break;
                        case 'zremrangebyscore': return C::redis()->zremrangebyscore($key, $value, $prefix); break;
            case 'zremrangebyrank': return C::redis()->zremrangebyrank($key, $value, $prefix); break;
			case 'set': return C::redis()->set($key, $value, $ttl, $prefix); break;
			case 'get': return C::redis()->get($key, $value); break;
			case 'rm': return C::redis()->rm($key, $value); break;
			case 'inc': return C::redis()->inc($key, $value ? $value : 1); break;
			case 'dec': return C::redis()->dec($key, $value ? $value : -1); break;
		}
	}
	return null;
}

//获取额外字段
function otherlistfield($table){
	global $_G;
	if(!$table) return array();
	$data = array();
	if(is_array($table)){
		foreach($table as $m){
			$data[$m] = array();
			$r = DB::fetch_all("select otherfield from %t where `module` = %s ",array('common_field',$m));
			foreach($r as  $v){
				if(strlen($v['otherfield'])){
					$data[$m] = array_merge($data[$m],explode(',',$v['otherfield']));	
				}
			}
			$data[$m] = array_merge($data[$m],array('inputtime','updatetime','uid','status','display'));
		}
	}
	return $data;
}

//列表字段显示相关函数

//获取列表的status的值 用来分辨需要调用的显示字段内容
function get_list_type($data){
	if(!empty($data)){
		foreach($data as $key=>$val){
			foreach(explode('_orzd_',$key) as $ke=>$va){
				if(!empty($data[$key])||$data[$key]=='0'){
					$zdarray=explode('_zd_',$va);
					$zd=$zdarray[0];
					if(($zd=='status'||$zd=='pstatus')&&!in_array('not',$zdarray)){
						if(is_array($val)){
							$list_type=$val[0];
						}elseif(strlen($val)>0){
							$list_type_arr=explode(',',$val);
							$list_type=$val[0];	
						}
						return $list_type; 
					}
				}
				
			}
		}
	}
	return '-9'; 
}


//列表字段显示
function listfield($table,$all=0,$field = array(),$not='',$type=-9){
	global $_G;
	$_memberid = $_G['uid'];
	$fields = array();
	$tmpArr = array();
	$key = '';
	if(!$table) return $fields;
	if(is_array($table)){
		foreach($table as $m){			
			$Rtable = $m;			
			//$key = C::t('common_field')->get_primary($Rtable);
			$m = str_replace(DB_PRE,'',$m);		
			//$nfield[]= $key;
			//$num = C::t('common_field')->sfield($m, $field , $Memberid);
			$nfield = C::t('common_field')->get_fields($Rtable,0,$type);
			//var_dump($nfield);
			$i = 0;
			$preOrder = 0;
			foreach($nfield as $v){
				$f = $v['field'];
				$farr = get_fieldname($m, $f, $_memberid,$type);									
				if($farr[4]||$all||in_array($f,$field)){
					$fd[$m][$f]['key'] = $f;
					$fd[$m][$f]['name'] = $farr[0];
					$fd[$m][$f]['display'] = $farr[4];
					$fd[$m][$f]['width'] = $farr[1];
					$fd[$m][$f]['align'] = $farr[2];
					$fd[$m][$f]['type'] = $farr[3];
					$fd[$m][$f]['is'] = $farr[4];
					$fd[$m][$f]['order'] = $farr[5];
					$fd[$m][$f]['issearch'] = $farr[6];
					$fd[$m][$f]['isorder'] = $farr[10];
					$fd[$m][$f]['id'] = $farr[7]; 
					$tmpArr[$i] = $fd[$m][$f];
					$i++;						
				}
			}

			$fields =is_array($fd)? array_merge($fd,$fields):$fields;
		}
	}else{
		$m = $table;
		$m = !stristr(DB_PRE,$m)?DB_PRE.$m:$m;
		//$nfield = $db->get_fields($m);
//		if(is_array($nfield)){
//			foreach($nfield as $f){
//				$fd[$m][$f] = get_fieldname($m,$f);
//			}
//		}
	}
	$REfd = array($m=>array());
	//$tmpArr = listArr($tmpArr);
	foreach($tmpArr as $v){
		$REfd[$m][$v['key']] = $v;
	}
	return $REfd;			
}

//取字段信息
function get_fieldname($m,$field,$Memberid=0,$type=-9){

	//验证是否存在自己的设置
	$num = C::t('common_field')->sfield($m, $field , $Memberid);
	//var_dump($num);
	if($num){

		$Where="and userid='".$Memberid."' and type='".$type."' ";		
		$r = DB::fetch_first("select width,align,type,display,`order`,issearch,name,id,isorder from %t where `module` = %s and `field` = %s and userid = %d and type=%s", array('sfield', $m , $field , $Memberid ,$type));
		$r_ext = DB::fetch_first("select formtype,setting from %t where `module` = %s and `field` = %s",array('common_field',$m , $field));
		$r = array_merge($r, $r_ext);
	}else{
		$r = DB::fetch_first("select width,align,type,display,`order`,issearch,name,id,formtype,setting,isorder from %t where `module` = %s and `field` = %s",array('common_field',$m , $field));
	}
	
	if(!$r){
		$str[1] = 100;

		$str[2] = 'center';

		$str[3] = 'mk-9';

		$str[4] = 0;

		$str[5] = 0;

		$str[6] = 1;

		$str[0] = $field; 
		
		$str[7] = 0;
		
		$str[8] = ''; 
		
		$str[9] = '';
		
		$str[10] = 0;  
	}
	else {
		$str[1] = $r['width'];

		$str[2] = $r['align'];

		$str[3] = $r['type'];

		$str[4] = $r['display'];

		$str[5] = $r['order'];

		$str[6] = $r['issearch'];

		$str[0] = $r['name'];
		
		$str[7] = $r['id'];	
		
		$str[8] = $r['formtype'];
		
		$str[9] = $r['setting'];
		
		$str[10] = $r['isorder'];

	}
	return $str;
}

function listArr($Arr){
	$RArr = $Arr;
	$tArr = array('k'=>0,'o'=>0);
	$tmp = array();
	$c = count($Arr);
	$o = 0;
	for($k = $c; $k>=0; $k--){
		for($k2 = $k-1; $k2>=0 ; $k2--){
			if($Arr[$k-1]['order'] < $Arr[$k2-1]['order']){
	
				$NK = $k-1;
				$TK = $k2-1;
				$tmp = $Arr[$NK];
	
				for(; $NK > $TK; $NK-- ){				
					$Arr[$NK] = $Arr[$NK-1];				
				}				
				$Arr[$TK] = $tmp;
				$k2=$k;
			}
		}
	}
	return $Arr;
}

//按 模块取数据
function GetModuleDB($m, $field = '', $where = '',$type = 0)
{
	global $db;
	if(is_array($field)) $fields = implode(',',$field);
	else $fields = '*';
	if($where) $where = ' where '.$where;
	if($type==1){
		$tz = DB::fetch_all('select '.$fields.' from %t'.$where,array($m));
	}else{
		$tz = DB::fetch_first('select '.$fields.' from %t'.$where,array($m));
	}
	if($tz) return $tz;
	else return array();
}
//执行URL
function DoCurl($url , $post_data = array(), $httpCode = false ,$timeout = 5){
	//优先使用curl模式发送数据
	if (function_exists('curl_init') == 1){
		$curl = curl_init();	  
		curl_setopt ($curl, CURLOPT_URL, $url);
		curl_setopt ($curl, CURLOPT_HEADER,0);
		curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($curl, CURLOPT_REFERER, 'http://www.qq.com');
		curl_setopt ($curl, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
		curl_setopt ($curl, CURLOPT_TIMEOUT,$timeout);
		if($post_data) curl_setopt ($curl, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);   
		
		$get_content = curl_exec($curl);
		$http = curl_getinfo($curl,CURLINFO_HTTP_CODE);
		$type = curl_getinfo($curl,CURLINFO_CONTENT_TYPE); 
		if($get_content === false){
                    $get_content_error = 'Curl error: ' . curl_error($curl);
                }else{
                    $get_content_error = '';
                }
		curl_close ($curl);
	}
/*	else{
	  include(Webroot."/snoopy.php");
	  $snoopy = new snoopy();
	  $snoopy->referer = 'http://www.google.com/';//伪装来源
	  $snoopy->fetch($url);
	  $get_content = $snoopy->results;
	}*/
	if($httpCode) return array($http,$type , $get_content,$get_content_error);
	else return $get_content;
}

//列表字段显示函数结束

function libfile($libname, $folder = '') {
	$libpath = '/source/'.$folder;
	
	if(strstr($libname, '/')) {
		list($pre, $name) = explode('/', $libname);		
		$path = "{$libpath}/{$pre}/{$pre}_{$name}";
	} else {
		$path = "{$libpath}/{$libname}";
	}
	//var_dump($path);
	return preg_match('/^[\w\d\/_]+$/i', $path) ? realpath(SING_PATH.$path.'.php') : false;
}

function showmessage($message, $url_forward = '', $values = array(), $extraparam = array(), $custom = 0) {
	//require_once libfile('function/message');
	//return dshowmessage($message, $url_forward, $values, $extraparam, $custom);
	global $_G;
	if(!$url_forward) $url_forward = $message['url'];
	if(!$url_forward) $url_forward = 'javascript:history.go(-1);';
	if(is_ajax_request()) echo json_encode($message);
	else{
		$page_title = '提示信息';
		include admin_tpl('','showmessage');
	}
}

function dmkdir($dir, $mode = 0777, $makeindex = TRUE){
	if(!is_dir($dir)) {
		dmkdir(dirname($dir), $mode, $makeindex);
		@mkdir($dir, $mode);
		if(!empty($makeindex)) {
			@touch($dir.'/index.html'); @chmod($dir.'/index.html', 0777);
		}
	}
	return true;
}

function write_cache($content, $cachefile = ''){
	if(dmkdir(CACHE_PATH.'/'.dirname($cachefile))){
		if(!@$fp = fopen(CACHE_PATH.'/'.$cachefile.'.cache.php', 'w')) {
			//异常处理
		}
		flock($fp, 2);
		fwrite($fp, $content);
		fclose($fp);
	}
}

function write_trigger($content, $m ,$cachefile = ''){
	if(dmkdir(APP_ROOT.'/module/'.$m.'/trigger/'.dirname($cachefile))){
		if(!@$fp = fopen(APP_ROOT.'/module/'.$m.'/trigger/'.$cachefile.'.trigger', 'w')) {
			//异常处理
		}
		flock($fp, 2);
		fwrite($fp, $content);
		fclose($fp);
	}
}

function string2array($data) {
	if($data == '') return array();
	$array = unserialize($data);
	return $array;
}
function array2string($data) {
	if(!is_array($data)) return $data;
	$string = serialize($data);
	return $string;
}

function multi($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $autogoto = FALSE, $simple = FALSE, $jsfunc = FALSE) {
	return $num > $perpage ? helper_page::multi($num, $perpage, $curpage, $mpurl, $maxpages, $page, $autogoto, $simple, $jsfunc) : '';
}
//创建随机数
function rand_str($pw_length = 8,$A=false)
{
	$randpwd = '';
	for ($i = 0; $i < $pw_length; $i++) 
	{
		$randpwd .= $A?chr(mt_rand(65, 90)):chr(mt_rand(33, 126));
	}
	return $randpwd;
}
function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

function is_weixin(){
	if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false )	return true;		
	return false;
}

function urlJump($url, $xssurl = false){
	global $_G;
	$r = $_G['isHTTPS']?stripos($url, 'https://'):stripos($url, 'http://');
	$s = stripos($url, $_G['HOST_URL']);
	if($xssurl) {
		header('Location: '.$url);
		exit;
	}	
	if($s === 0 && $r !== false){
		header('Location: '.$url);
		exit;
	}
	if($r === false){
		header('Location: '.$url);
		exit;
	}
}

function DoPreg($t1 ='' ,$url ,$t3 ='',$t4 =''){
		if(stripos($url,"javascript:") !== false ) return '<a'.stripslashes($t1).'href="'.$url.'"'.stripslashes($t3).'>'.stripslashes($t4).'</a>';
		$s = stripos($url,"#");
		if($s !== false){
			$url_ext = substr($url,$s,strlen($url));
			$url = substr($url,0,$s);			
		}		
		$tmp = array('iframe=1');
		
		if(stripos($url,$tmp[0]) === false){
			if(stripos($url,'?') === false) $url .= '?'.$tmp[0];
			else $url .= '&'.$tmp[0];
		}

		return '<a'.stripslashes($t1).'href="'.$url.$url_ext.'"'.stripslashes($t3).'>'.stripslashes($t4).'</a>';
	}

function pt_output(){
	
	if(!$_GET['iframe']) return;
	global $_G;
	if(defined('SING_OUTPUTED')) {
		return;
	} else {
		define('SING_OUTPUTED', 1);
	}
	$content = ob_get_contents();
	ob_end_clean();
	$_G['gzipcompress'] ? ob_start('ob_gzhandler') : ob_start();
	$Pattern='/<a([\s\S]*?)href=[\'|\"](.*?)[\'|\"]([\s\S]*?)>([\s\S]*?)<\/a>/ie';
	$content = preg_replace($Pattern,"DoPreg('\\1','\\2','\\3','\\4')",$content);
	echo $content;
}

function output() {

	global $_G;
	if(defined('SING_OUTPUTED')) {
		return;
	} else {
		define('SING_OUTPUTED', 1);
	}
	
	/*
	if(!empty($_G['blockupdate'])) {
		block_updatecache($_G['blockupdate']['bid']);
	}

	if(defined('IN_MOBILE')) {
		mobileoutput();
	}
	if(!defined('IN_MOBILE') && !defined('IN_ARCHIVER')) {
		$tipsService = Cloud::loadClass('Service_DiscuzTips');
		$tipsService->show();
	}
	$havedomain = implode('', $_G['setting']['domain']['app']);
	*/
	//if($_G['setting']['rewritestatus'] || !empty($havedomain)) {
		$content = ob_get_contents();
		//$content = output_replace($content);

	
		ob_end_clean();
		$_G['gzipcompress'] ? ob_start('ob_gzhandler') : ob_start();
		$is_common = !$_G['inajax'] && !defined('SING_Ajax') && stripos($content, 'DWZ.init')===false;		
		if($is_common){

			include admin_tpl('','header_common');
			include admin_tpl('','common');

			echo '<script type="text/javascript">
			$(function(){
				DWZ.init("ui/dwz.frag.xml", {
					AdminUrl:"admin.php",
					loginUrl:"login_dialog.html", loginTitle:"登录",
					statusCode:{ok:200, error:300, timeout:301},
					pageInfo:{page:"pageNum", numPerPage:"numPerPage", orderField:"orderField", orderDirection:"orderDirection"},
					keys: {statusCode:"statusCode", message:"message"},
					debug:false,
					callback:function(){
						initEnv();
						$("#themeList").theme({themeBase:"ui/themes"});
					}
				});
			});
			</script>
			
			
			</head>
			
			<body>
			<div class="bd">
			';
		}
		
		echo $content;	
		if($is_common)	echo '
		</div>
		</body>
</html>';
		
	//}

	/*if(isset($_G['makehtml'])) {
		helper_makehtml::make_html();
	}

	if($_G['setting']['ftp']['connid']) {
		@ftp_close($_G['setting']['ftp']['connid']);
	}
	$_G['setting']['ftp'] = array();

	if(defined('CACHE_FILE') && CACHE_FILE && !defined('CACHE_FORBIDDEN') && !defined('IN_MOBILE') && !checkmobile()) {
		if(diskfreespace(DISCUZ_ROOT.'./'.$_G['setting']['cachethreaddir']) > 1000000) {
			if($fp = @fopen(CACHE_FILE, 'w')) {
				flock($fp, LOCK_EX);
				fwrite($fp, empty($content) ? ob_get_contents() : $content);
			}
			@fclose($fp);
			chmod(CACHE_FILE, 0777);
		}
	}

	if(defined('DISCUZ_DEBUG') && DISCUZ_DEBUG && @include(libfile('function/debug'))) {
		function_exists('debugmessage') && debugmessage();
	}*/
}

function getsqlstr($field,$type,$value){
	$lsstr = '';
	$lsarr = array();
	if($field&&$type&&(in_array($type,array(11,12,13,14))||$value)){
		switch($type){
			case '1':
				$lsstr = ' '.$field.'  = \''.$value.'\' ';
				break;
			case '2':
				$lsstr = '  '.$field.' != \''.$value.'\' ';
				break;
			case '3':
				$lsstr = '  '.$field.'  < \''.$value.'\' ';
				break;
			case '4':
				$lsstr = '  '.$field.'  <= \''.$value.'\' ';
				break;
			case '5':
				$lsstr = '  '.$field.'  > \''.$value.'\' ';
				break;
			case '6':
				$lsstr = '  '.$field.'  >= \''.$value.'\' ';
				break;
			case '7':
				$lsstr = '  '.$field.'  LIKE \'%'.$value.'%\' ';
				break;
			case '8':
				$lsstr = '  '.$field.'  NOT LIKE \'%'.$value.'%\' ';
				break;
			case '9':
				$lsstr = '  '.$field.'  LIKE \''.$value.'%\' ';
				break;
			case '10':
				$lsstr = '  '.$field.'  LIKE \'%'.$value.'\' ';
				break;
			case '11':
				$lsstr = ' `'.$lsarr[0].'  IS NULL ';
				break;
			case '12':
				$lsstr = '  '.$field.'  IS NOT NULL ';
				break;
			case '13':
				$lsstr = '  '.$field.'  = \'\' ';
				break;
			case '14':
				$lsstr = '  '.$field.'  != \'\' ';
				break;
			case '15':
				$ls_2arr = explode(',',$value);
				if(count($ls_2arr)==2){
					$lsstr = '  '.$field.'  BETWEEN \''.$ls_2arr[0].'\' AND \''.$ls_2arr[1].'\' ';
				}
				break;
			case '16':
				$ls_2arr = explode(',',$value);
				if(count($ls_2arr)==2){
					$lsstr = '  '.$field.'  NOT BETWEEN \''.$ls_2arr[0].'\' AND \''.$ls_2arr[1].'\' ';
				}
				break;
			case '17':
				$ls_2arr = explode(',',$value);
				$ls_2str = implode('\',\'',$ls_2arr);
				if($ls_2str){
					$lsstr = '  '.$field.'  IN ('.$ls_2str.') ';
				}
				break;
			case '18':	
				$ls_2arr = explode(',',$value);
				$ls_2str = implode('\',\'',$ls_2arr);
				if($ls_2str){
					$lsstr = '  '.$field.'  NOT INT ('.$ls_2str.') ';
				}
				break;
		}	
	}
	return $lsstr;
}
function unescape($str) 
{ 
    $ret = ''; 
    $len = strlen($str); 
    for ($i = 0; $i < $len; $i ++) 
    { 
        if ($str[$i] == '%' && $str[$i + 1] == 'u') 
        { 
            $val = hexdec(substr($str, $i + 2, 4)); 
            if ($val < 0x7f) 
                $ret .= chr($val); 
            else  
                if ($val < 0x800) 
                    $ret .= chr(0xc0 | ($val >> 6)) . 
                     chr(0x80 | ($val & 0x3f)); 
                else 
                    $ret .= chr(0xe0 | ($val >> 12)) . 
                     chr(0x80 | (($val >> 6) & 0x3f)) . 
                     chr(0x80 | ($val & 0x3f)); 
            $i += 5; 
        } else  
            if ($str[$i] == '%') 
            { 
                $ret .= urldecode(substr($str, $i, 3)); 
                $i += 2; 
            } else 
                $ret .= $str[$i]; 
    } 
    return $ret; 
}
//系统分类下拉菜单	
function classilist($location,$parentid=0,$n=1,$now=0){
	global $db;
	$tmp= '';
	$loop = '';
	$where=$location?' and find_in_set(\''.$location.'\',location)':'';//显示位置
	$rs = DB::fetch_all("select * from %t where parentid=%d and status=1 and display=1 %i order by turn desc",array('classi',$parentid,$where));
	for($i=1;$i<$n;$i++){
		$tmp.='&nbsp;&nbsp;&nbsp;&nbsp;';
	}
	foreach($rs as $r){
		if($r['classiid'] == $now) $select = ' selected="selected"';
		else $select = '';
		$loop = $loop.'<option value="'.$r['classiid'].'"'.$select.'>'.$tmp.$r['classiname'].'</option>'.classilist($location,$r['classiid'],$n+1,$now);
	}
	return $loop;
}
//获取 营销所有部门id
function yxde($id=YX_ID){
	$sql_deid=DB::fetch_first('select * from %t where deid=%d',array('department',$id));
	if($sql_deid['descendants']){
		$deid_des=explode(',',$sql_deid['descendants']);
		$deid_arr=array();
		foreach(explode(',',$sql_deid['child'])?explode(',',$sql_deid['child']):array() as $key_d => $val_d){
			$sql_dename=DB::fetch_first('select * from %t where deid=%d',array('department',$val_d));
			$descend=$sql_dename['descendants']?$sql_dename['descendants'].','.$val_d:$val_d;
			$deid_arr[$val_d]=array('id'=>$val_d,'name'=>$sql_dename['dename'],'des'=>$descend);
		}
		$yxdeid=array('deidarr'=>$deid_des,'deidstr'=>$sql_deid['descendants'],'dearr'=>$deid_arr);
	}else{
		$yxdeid=array();
	}	
	return $yxdeid;
}

function thnullzd($str='',$th='--'){
	return strlen($str)?$str:$th;	
}
//pid parentid  
function getdepartments($pid = 0 ,$isc = 0){
	$deidarr = array();
	$deall = DB::fetch_all('select deid,parentid from %t where parentid=%d and display=1',array('department',intval($pid))); 
	foreach($deall as $v){
		$deidarr[] = $v['deid'];
		if(!$isc){
			$lsdearr = getdepartments($v['deid']);
			if(is_array($deidarr) && is_array($lsdearr)) $deidarr = array_merge($deidarr,$lsdearr);	
		}
	}
	return $deidarr;
}
//新权限判断
function checkmysa($m='',$p='',$id=0,$table=''){
	if(!$m || !$p) return false;	//参数不对
	global $_G;
	if($_G['adminid'] == $_G['uid']) return true;
	$mysa = $_G['mysa'];
	$ywidarr = array('yewuid','salesid','sales_id','yywuid','uid','addmemberid');
	if($id){
		$table = $table?$table:$m;
		if(!DB::CheckTable($table)) return false; //数据库不存在
		$fields = DB::get_fields($table);	
		if(!is_array($fields)) return false;	//数据库中没有字段
		$ywidzd = '';
		foreach($ywidarr as $z){
			if(in_array($z,$fields)){
				$ywidzd = $z;
				break;
			}
		}
		if(!$ywidzd) return false;	//数据库中没有 定义的 业务员id
		$primary = DB::get_primary($table);
		if(!$primary) return false;	//数据库用没有 主键
		$ids = is_array($id)?$id:array($id);	
		$ywid = DB::result_first('select '.$ywidzd.' from %t where '.$primary.' in (%n)',array($table,$ids));
		if(!$ywid) return true; //判断业务员id 没有业务员 则都有权限
		$mysa['module'][$m][$p] = is_array($mysa['module'][$m][$p])?$mysa['module'][$m][$p]:array();
		$mysa['ids']['memberid'] = is_array($mysa['ids']['memberid'])?$mysa['ids']['memberid']:array(); 
		if(in_array($ywid,$mysa['module'][$m][$p]) || !in_array($ywid,$mysa['ids']['memberid'])) return true;  //判断业务员id 在权限之内 或者 没在数据库中 则有权限
		else{
			if(in_array('uid',$fields)&&$p=='view'&&$m=='customers'){
				$uid = DB::result_first('select uid from %t where '.$primary.' in (%n)',array($table,$ids));
				if(!$uid) return false; 
				$mysa['module'][$m][$p] = is_array($mysa['module'][$m][$p])?$mysa['module'][$m][$p]:array();
				$mysa['ids']['memberid'] = is_array($mysa['ids']['memberid'])?$mysa['ids']['memberid']:array(); 
				if(in_array($uid,$mysa['module'][$m][$p]) || !in_array($uid,$mysa['ids']['memberid'])) return true;	
			}
			return false;
		}
	}else{
		// else 中为没传id 只判断有没有权限  比如 添加权限
		if(empty($mysa['module'][$m][$p])){
			return false;
		}else{
			return true;	
		}
	}
}

//创建二维码
function getWxTicket($_mid,$use,$type = 0,$scene_id = '',$who = '') {
	if($access_token = active_check_access_token($_mid)){
		if($type){//固定二维码
			if(empty($scene_id)) return false;
			$str = '{"action_name":"QR_LIMIT_SCENE","action_info":{"scene":{"scene_id":'.$scene_id.'}}}';
		}else{//临时二维码
			$str = '{"expire_seconds":604800,"action_name":"QR_SCENE","action_info":{"scene":{"scene_id":'.md5(TIME).'}}}';
		}
		$d = active_curl('https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token,$str);
		if(!$d['errcode'] && $d['ticket']){
			$ticket = rand_str(20,true);
			DB::insert('wx_ticket',array('tid'=>$ticket,'ticket'=>$d['ticket'],'type'=>$type,'mid'=>$_mid,'inputtime'=>TIME,'use'=>$use,'who'=>$who,'url'=>$d['url']));
			$d['ticket'] = urlencode($d['ticket']);
			return $d['ticket'];
		}else{
			//echo $access_token;
			//echo $d['errcode'];
			return false; //'错误代码'.$d['errcode'];	
		}
	}else{
		return false;
	}
}




/*-------------API接收参数自动处理json格式 直接操作get和post所以放在核心函数库里 2015年12月29日 14:32:09--------------------*/

function checkJsonToJson($str){
    $return = $str;
    //echo $str;
    //var_dump(is_string($str));
    $pattern1 = '/^\[[\s\S]*\]$/';
    $pattern2 = '/^\{[\s\S]*\}$/';
    if(is_string($str) && (preg_match($pattern1,$return) || preg_match($pattern2,$return))){
        $json = json_decode($str,true);
        $return = $json?$json:$str;
    }
    return $return;
}

function convertJsonStringToJsonArray($val){
    //var_dump(is_array($val));
    if(is_array($val)){
        foreach($val as $k=>$v){
            $val[$k] = convertJsonStringToJsonArray($v);
        }
    }else{
        $val = checkJsonToJson($val);
    }
    return $val;
}

/*------------API end------------------*/

/*---------------------------*/
function redis($cmd,$key,$value=null){
	$redis = redis_class::instance();
	switch ($cmd) {
		case 'sadd': return $redis->sadd($key,$value); break; //添加单个成员 返回生效条数
		case 'srem': return $redis->srem($key,$value); break; //移除单个成员 返回生效条数
		case 'scard': return $redis->scard($key); break; //返回总数
		case 'sismember': return $redis->sismember($key,$value); break; //判断成员是否在集合中 返回 0 或 1
		case 'set': return $redis->set($key,$value); break; //设置 $key 对应的$value
		case 'get': return $redis->get($key,$value); break; //根据$key 读取对应的$value 读取数据必须是字符串
		
	}
}
/*--------bug提交方法--------*/
/*
sourcetype 发生的类名 
sourcetype_info 发生问题位置和情况的描述
rescued 补救的位置
*/
function addBugLog($sourcetype,$sourcetype_info,$rescued){
	$insert = array();
	$insert['inputtime'] = TIME;
	$insert['sourcetype'] = $sourcetype;
	$insert['sourcetype_info'] = $sourcetype_info;
	$insert['rescued'] = $rescued;
	DB::SetMainDB(DB_ESHOP);
	DB::insert('es_buglog',$insert);
}
/*----------------*/

function JSON($array) {
        arrayRecursive($array, 'urlencode', true);
        $json = json_encode($array);
        return urldecode($json);
}
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
        static $recursive_counter = 0;
        if (++$recursive_counter > 1000) {
                die('possible deep recursion attack');
        }
        foreach ($array as $key => $value) {
                if (is_array($value)) {
                        arrayRecursive($array[$key], $function, $apply_to_keys_also);
                } else {
                        $array[$key] = $function($value);
                }

                if ($apply_to_keys_also && is_string($key)) {
                        $new_key = $function($key);
                        if ($new_key != $key) {
                                $array[$new_key] = $array[$key];
                                unset($array[$key]);
                        }
                }
        }
        $recursive_counter--;
}

